
var options,
	groupsDropdown = null,
	hiddenWorkoutsSelector,
	imperialSystem,
	oneRepMaxesDisplayed = false;

function $(id) {
	return document.getElementById(id);
}

function calc1RepMax(reps, weight) {
	// Brzycki Formula
	if (reps <= 10) {
		return Math.round(weight * 36 / (37 - reps));
	}
	else {
		return 0;
	}
};

function onDOMNodeInserted(e) {
	if (!e.target)
		return;
	if (options.display1RMInFeed) {
		display1RepMaxes(e.target);
	}
	if (options.groupsDropdown) {
		setupGroupsDropdown();
	}
	if (options.hideWorkouts) {
		setupExpandWorkout(e.target);
	}
	/*console.log(e.target.tagName + ' ' + e.target.id);
	if (e.target.getElementById && e.target.getElementById('history_activity_chooser')) {
		setupHistoryExport();
	}*/
}

function setup1RepMaxes() {
	var scripts = document.head.querySelectorAll('script:not([src])');
	for (var i = 0; i < scripts.length; i++) {
		if (scripts[i].innerHTML.indexOf('var imperial') > -1) {
			eval(scripts[i].innerHTML);
			imperialSystem = imperial;
		}
	}
}

function display1RepMaxes(elem) {
	/*if (oneRepMaxesDisplayed || !$('activity_stream_content'))
		return;
	oneRepMaxesDisplayed = true;*/
	if (!elem.getElementsByClassName || elem.getElementsByClassName('action_detail').length == 0) return;
	var lis = document.querySelectorAll('ul.action_detail ul li'),
		spanClass = imperialSystem ? 'set_user_imperial' : 'set_user_metric';
	window.removeEventListener('DOMNodeInserted', onDOMNodeInserted);
	try {
		for (var i = 0; i < lis.length; i++) {
			var spans = lis[i].getElementsByClassName(spanClass),
				spanSet = spans.length == 1 ? spans[0] : null;
			if (spanSet && spanSet.textContent.indexOf('reps') > -1) {
				var setData = spanSet.textContent.split(' x '),
					weightUnit = setData[0].split(' ').pop();
				if (weightUnit == 'kg' || weightUnit == 'lb') {
					var weight = parseFloat(setData[0]),
						reps = parseFloat(setData[1]);
					if (reps <= 10) {
						lis[i].innerHTML += ' <span class="set_1rm"> - 1RM: ' + calc1RepMax(reps, weight) + ' ' + weightUnit + '</span>';
					}
				}
			}
		}
	} finally {
		window.addEventListener('DOMNodeInserted', onDOMNodeInserted);
	}
};

function getGroups() {
	var groupItems = false;
	if ($('group_id'))
		groupItems = $('group_id').options;
	if (!groupItems && $('profile-group-joined-table'))
		groupItems = $('profile-group-joined-table').getElementsByTagName('a');
	if (!groupItems && $('my_groups'))
		groupItems = $('my_groups').getElementsByClassName('group_title');
	if (groupItems) {
		var groups = [],
			groupItem, groupId;
		for (var i=0; i<groupItems.length; i++) {
			groupItem = groupItems[i];
			if (groupItem.tagName == 'A' && groupItem.href.indexOf('/group/') > -1) {
				groupId = groupItem.href.replace(/.*group\/(\d+).*/, '$1');
			} else if (groupItem.tagName == 'OPTION') {
				groupId = groupItem.value;
			} else {
				groupId = false;
			}
			if (groupId) {
				groups.push({
					id: groupId,
					name: groupItem.textContent
				});
			}
		}
		localStorage.fcGroups = JSON.stringify(groups);
	}
	if (localStorage.fcGroups)
		return JSON.parse(localStorage.fcGroups);
	else
		return false;
}

function displayGroupsDropdown() {
	groupsDropdown.style.display = 'block';
}

function hideGroupsDropdown() {
	groupsDropdown.style.display = 'none';
}

function setupGroupsDropdown() {
	if (groupsDropdown) return;
	var groups = getGroups();
	if (groups && groups.length) {
		groupsDropdown = document.createElement('div');
		groupsDropdown.setAttribute('id', 'groups-dropdown');
		for (var i=0; i<groups.length; i++) {
			groupsDropdown.innerHTML += '<a href="/group/' + groups[i].id + '/">' + groups[i].name + '</a>';
		}
		var miGroups = $('groups');
		miGroups.addEventListener('mouseover', displayGroupsDropdown);
		miGroups.addEventListener('mouseout', hideGroupsDropdown);
		miGroups.appendChild(groupsDropdown);
	}
}

function setupHiddenWorkouts() {
	var style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = 'ul.action_detail li { display: none; }'
		+ 'a.expand_workout { cursor: pointer; display: inline; float: right; }';
	document.head.appendChild(style);
}

function setupExpandWorkout(elem) {
	if (!elem.getElementsByClassName) return;
	var actions = elem.getElementsByClassName('action');
	for (var i=0; i<actions.length; i++) {
		var action = actions[i],
			actionDetail = action.getElementsByClassName('action_detail')[0],
			actionPrompts;
		if (!actionDetail)
			continue;
		actionPrompts = actionDetail.getElementsByClassName('action_prompt')
		if (actionPrompts.length > 0) {
			
			// Workout summary
			var sExercises = '';
			for (var j=0; j<actionPrompts.length; j++) {
				if (j > 0) sExercises += ', ';
				sExercises += actionPrompts[j].textContent.replace(/:$/, '');
			}
			sExercises = sExercises.replace(/,([^,]*)$/, ' and $1');
			actionDetail.previousSibling.textContent = actionDetail.previousSibling.textContent.replace('for:', 'for');
			action.insertBefore(document.createElement('span'), actionDetail);
			actionDetail.previousSibling.outerHTML = '<span class="collapsed"> ' + sExercises + '.</span>'
			
			// Creates "Expand" links
			var expandLink = document.createElement('a');
			expandLink.className = 'expand_workout gray_icon_link';
			expandLink.textContent = 'Expand';
			expandLink.addEventListener('click', function(event) {
				this.dataset.expanded = this.dataset.expanded ? '' : 'expanded';
				var lis = this.parentNode.getElementsByTagName('li'),
					collapsedLabel = this.parentNode.getElementsByClassName('collapsed')[0];
				for (var j=0; j<lis.length; j++) {
					lis[j].style.display = this.dataset.expanded ? 'list-item' : 'none';
				}
				collapsedLabel.style.display = this.dataset.expanded ? 'none' : 'inline';
				this.textContent = this.dataset.expanded ? 'Collapse' : 'Expand';
			});
			action.insertBefore(expandLink, action.firstChild);
		}
	}
}

chrome.extension.sendRequest({type: 'getOptions'}, function(response) {	
	options = response;
	if (options.groupsDropdown) {
		setupGroupsDropdown();
	}
	if (options.display1RMInFeed) {
		setup1RepMaxes();
		//console.log(imperialSystem);
	}
	if (options.hideWorkouts && location.pathname.indexOf('/view_workout/') == -1) {
		setupHiddenWorkouts();
		setupExpandWorkout(document);
	}
	window.addEventListener('DOMNodeInserted', onDOMNodeInserted);
});

function loadUserProfile(userId, callback) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', 'http://www.fitocracy.com/userprofile/' + userId + '/', true);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			callback(xhr.responseText);
		}
	}
	xhr.send();     
}

function getActivityHistory(activityId, callback) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', 'http://www.fitocracy.com/get_history_json_from_activity/' + activityId + '/?max_sets=-1&max_workouts=-1', true);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			callback(JSON.parse(xhr.responseText));
		}
	}
	xhr.send();
}

function getUserId() {
	var userId = localStorage['userId'];
	if (userId) {
		return userId;
	} else {
		var profile_user_id = $('profile_user_id');
		if (profile_user_id && profile_user_id.value) {
			localStorage['userId'] = profile_user_id.value;
			return profile_user_id.value;
		}
	}
}

function historyExportLinkOnClick() {
	var activityId = $('history_export_activity_chooser').value;
	$('history_export_link').textContent = 'Exporting...';
	getActivityHistory(activityId, function(data) {
		var i, j, k, workout, action, csvData = '', actionKeys = [];
		$('history_export_link').textContent = 'Export history';
		for (i in data) {
			workout = data[i];
			for (j in workout.actions) {
				action = workout.actions[j];
				// header
				if (i == 0 && j == 0) {
					for (k in workout)
						if (k != 'actions')
							csvData += 'workout_' + k + ',';
					for (k in action)
						actionKeys.push(k);
					actionKeys.sort();
					for (k=0; k<actionKeys.length; k++)
						csvData += 'action_' + actionKeys[k] + ',';						
				}
				// data
				csvData += '\n';
				for (k in workout)
					if (k != 'actions')
						csvData += workout[k] + ',';
				for (k=0; k<actionKeys.length; k++)
					csvData += action[actionKeys[k]] + ',';
			}
		}
		$('history_export_data').innerHTML += csvData;
	});
}

function setupHistoryExport() {
	var historyContainer = $('history_container');
	if (!historyContainer)
		return;
	var historyExportActivityChooser = $('history_activity_chooser').cloneNode(),
		allOption = document.createElement('option');
	historyExportActivityChooser.id = 'history_export_activity_chooser';
	allOption.value = '0';
	allOption.text = 'All activities';
	historyExportActivityChooser.add(allOption);
	historyContainer.innerHTML += '<hr><div id="history_export">'
		+ '<h3>Export</h3>'
	historyContainer.appendChild(historyExportActivityChooser);
	historyContainer.innerHTML += '<p><a id="history_export_link" style="cursor: pointer">Export history</a></p>'
		+ '<p><textarea id="history_export_data" style="width: 100%; height: 200px"></textarea>'
		+ '</div>';
	$('history_export_link').addEventListener('click', historyExportLinkOnClick);
}

